package android.coocoo.views;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Intent;
import android.content.res.Resources;
import android.coocoo.common.Const;
import android.coocoo.common.XmlParser;
import android.coocoo.controller.AlarmBroadcastReceiver;
import android.coocoo.controller.ReminderService;
import android.coocoo.models.CategoryInfo;
import android.coocoo.models.Settings;
import android.coocoo.models.TaskInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TabHost;

public class DisplayTasksListActivity extends TabActivity {
	
	static ArrayList<PendingIntent> mAlarmSender = null;
	static AlarmManager am = null;
	
	ArrayList<TaskInfo> tasksList;
	ArrayList<CategoryInfo> categoriesList;
	XmlParser xmlParser;
	Settings settings;
	
	ImageView btSetting;
	ImageView btAdd;
	TabHost tabHost;
	TabHost.TabSpec spec0;
	TabHost.TabSpec spec1;
	Resources res;
	boolean flPaused;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_tasks_list);
		
		res = getResources();
		xmlParser = new XmlParser();
		flPaused = false;
		
		this.tasksList = xmlParser.getTasksList();
		this.settings = xmlParser.getSettings();
		this.categoriesList = xmlParser.getCategoriesList();
		
		btSetting = (ImageView)findViewById(R.id.btSetting);
		btSetting.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(DisplayTasksListActivity.this, DisplaySettingInfoActivity.class);
				i.putExtra("settings", settings);
				i.putExtra("categoriesList", categoriesList);
				startActivityForResult(i, Const.Request.GET_SETTINGS);
			}
		});
		
		btAdd = (ImageView)findViewById(R.id.btAdd);
		btAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(DisplayTasksListActivity.this,
										DisplayTaskInfoActivity.class);
				TaskInfo taskInfo = new TaskInfo();
				i.putExtra("task", taskInfo);
				i.putExtra("categoriesList", categoriesList);
				startActivityForResult(i, Const.Request.ADD_TASK);
			}
		});
		
		tabHost = getTabHost();
	    Intent intent;  // Reusable Intent for each tab

	    // Create an Intent to launch DisplayTasksListByDateActivity for the tab
	    intent = new Intent().setClass(this, DisplayTasksListByDateActivity.class);
	    intent.putParcelableArrayListExtra("tasksList", tasksList);
	    intent.putParcelableArrayListExtra("categoriesList", categoriesList);
	    // Initialize a TabSpec for each tab and add it to the TabHost
	    spec0 = tabHost.newTabSpec(res.getString(R.string.BY_DATE))
	    				.setIndicator(res.getString(R.string.Date), res.getDrawable(R.drawable.icon_tab_bydate))
	    				.setContent(intent);
	    tabHost.addTab(spec0);
	    
	    // Create an Intent to launch DisplayTasksListByCategoryActivity for the tab
	    intent = new Intent().setClass(this, DisplayTasksListByCategoryActivity.class);
	    intent.putParcelableArrayListExtra("tasksList", tasksList);
	    intent.putParcelableArrayListExtra("categoriesList", categoriesList);
	    spec1 = tabHost.newTabSpec(res.getString(R.string.BY_CATEGORY))
	    				.setIndicator(res.getString(R.string.Category), res.getDrawable(R.drawable.icon_tab_bycategory))
	    				.setContent(intent);
	    tabHost.addTab(spec1);

	    tabHost.setCurrentTab(0);
		
	}

	@Override
	protected void onPause() {
		flPaused = true;
		super.onPause();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		System.out.println("Result code = " + resultCode);
		if (requestCode == Const.Request.GET_SETTINGS){
			if (resultCode == Const.Result.SUCCESS){
				this.settings = intent.getParcelableExtra("returnSettings");
				this.categoriesList = intent.getParcelableArrayListExtra("returnCategoriesList");
				this.xmlParser.setSettings(this.settings);
				this.xmlParser.setCategoriesList(this.categoriesList);
			}else{
				
			}
		} else if (requestCode == Const.Request.ADD_TASK){
			if (resultCode == Const.Result.SUCCESS)
			{
				TaskInfo taskInfo = (TaskInfo)intent.getParcelableExtra("returnTask");
				Log.e("pass_flag", "New task is added.");
				this.tasksList.add(taskInfo);
				this.xmlParser.setTasksList(tasksList);
			}else{
			}
		}
	}
	
	@Override
	protected void onResume() {
//		if (tasksList != null)
//			if (tasksList.size()>0){
////		         Schedule the alarm!
//				if (am == null)
//					am = (AlarmManager)getSystemService(ALARM_SERVICE);
//				else{
//					int i;
//					for (i=0; i<mAlarmSender.size(); i++)
//						am.cancel(mAlarmSender.get(i));
//					mAlarmSender = null;
//				}
//				if (mAlarmSender == null)
//					mAlarmSender = new ArrayList<PendingIntent>();
//		        int i;
//		        for (i=0; i<tasksList.size(); i++){
//		        	Date startTime = (Date) tasksList.get(i).getStartTime().clone();
//		        	startTime.setMinutes(startTime.getMinutes()-tasksList.get(i).getBefore());
//		        	Intent intent = new Intent(DisplayTasksListActivity.this, ReminderService.class);
//		        	intent.putExtra("task", tasksList.get(i));
//		        	mAlarmSender.add(PendingIntent.getService(DisplayTasksListActivity.this,
//			                0, intent, 0));
//			        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime.getTime(), mAlarmSender.get(i));
//		        }
//			}
//		if (tasksList != null){
//			if (tasksList.size() > 0){
//				
//				int i;
//				for (i=0; i<tasksList.size(); i++){
//					Intent intent = new Intent(DisplayTasksListActivity.this, AlarmBroadcastReceiver.class);
//					PendingIntent sender = PendingIntent.getBroadcast(DisplayTasksListActivity.this, Const.Request.SCHEDULE_ALARM, intent, 0);
//					
//					Calendar calendar = Calendar.getInstance();
//					calendar.setTimeInMillis(tasksList.get(i).getStartTime().getTime());
//					calendar.add(Calendar.MINUTE, (-tasksList.get(i).getBefore()));
//					
//					AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//					alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//
//				}
//			}else{
//				Log.e("list.size = 0", "Returned taskList size is 0. No service is started.");
//			}
//		}else{
//			Log.e("null pointer", "Returned taskList is null. No service is started.");
//		}
		if (this.settings.isTurnOff()){
			Log.e("DisplayTasksListActivity resume", "Reminder is turned off");
			Intent intent = new Intent(DisplayTasksListActivity.this, ReminderService.class);
			if (isReminderServiceRunning()){
				stopService(intent);
			}
		}else{
			if (tasksList != null){
				if (tasksList.size() > 0){
					Intent intent = new Intent(DisplayTasksListActivity.this, ReminderService.class);
					intent.putExtra("tasksList", tasksList);
					if (isReminderServiceRunning()){
						stopService(intent);
					}
					startService(intent);
				}else{
					Log.e("list.size = 0", "Returned taskList size is 0. No service is started.");
				}
			}else{
				Log.e("null pointer", "Returned taskList is null. No service is started.");
			}
		}
		super.onResume();
	}

	private boolean isReminderServiceRunning() {
		ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : activityManager.getRunningServices(Integer.MAX_VALUE)) {
			if ("android.coocoo.controller.ReminderService".equals(service.service.getClassName())) {
				Log.e("starting service","service has already been running");
				return true;
			}
		}
		return false;
	}
}